<template>
  <div class="user-info-container">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="120px" inline>
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.buyerUserId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input v-model="searchForm.userAccount" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select v-model="searchForm.state" placeholder="请选择用户状态" clearable style="width: 80px;">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否黑名单">
          <el-select v-model="searchForm.isBlack" placeholder="请选择是否黑名单" clearable style="width: 80px;">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="registerTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="注册开始时间"
            end-placeholder="注册结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="buyerUserId" label="用户ID" width="100" />
        <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-image 
              :src="scope.row.headImage" 
              style="width: 40px; height: 40px"
              fit="cover"
              preview-teleported
              :preview-src-list="[scope.row.headImage]"
            >
              <template #error>
                <div class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="昵称" width="120" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="scope">
            <span>{{ scope.row.sex || '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="userAccount" label="用户账号" width="120" />
        <el-table-column prop="password" label="登录密码" width="120" />
        <el-table-column prop="state" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.state === 1 ? 'success' : 'danger'">
              {{ scope.row.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ifBlack" label="黑名单" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.ifBlack === 1 ? 'danger' : 'success'">
              {{ scope.row.ifBlack === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="个人简介" show-overflow-tooltip />
        <el-table-column prop="province" label="省份" width="100" />
        <el-table-column prop="city" label="城市" width="100" />
        <el-table-column prop="createTime" label="注册时间" width="160" />
        <el-table-column prop="authStatus" label="实名认证状态" width="120">
          <template #default="scope">
            <el-tag :type="getAuthStatusTagType(scope.row.authStatus)">
              {{ getAuthStatusText(scope.row.authStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360" fixed="right">
          <template #default="scope">
            <div style="display: flex; gap: 8px; flex-wrap: wrap;">
              <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="primary" @click="handleModifyPayPassword(scope.row)" style="min-width: 120px;">修改支付密码</el-button>
              <el-button v-if="scope.row.authStatus !== 0" size="small" type="info" @click="getAuthInfo(scope.row.buyerUserId)" style="min-width: 120px;">查看实名认证</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户信息编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editFormRef" 
        label-width="120px"
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="请选择生日"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="editForm.userAccount" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="editForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="editForm.province" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="editForm.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="editForm.state">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否黑名单" prop="ifBlack">
          <el-radio-group v-model="editForm.ifBlack">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="个人简介" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入个人简介"
          />
        </el-form-item>
        <el-form-item label="注册时间" v-if="editForm.createTime">
          <el-input v-model="editForm.createTime" disabled />
        </el-form-item>
        <el-form-item label="用户头像" v-if="editForm.headImage">
          <el-image 
            :src="editForm.headImage" 
            style="width: 100px; height: 100px"
            fit="cover"
            preview-teleported
            :preview-src-list="[editForm.headImage]"
          >
            <template #error>
              <div class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改支付密码对话框 -->
    <el-dialog 
      title="修改用户支付密码" 
      v-model="payPasswordDialogVisible" 
      width="500px"
      @close="handlePayPasswordDialogClose"
    >
      <el-form 
        :model="payPasswordForm" 
        :rules="payPasswordRules" 
        ref="payPasswordFormRef" 
        label-width="120px"
      >
        <el-form-item label="用户ID" prop="buyerUserId">
          <el-input v-model="payPasswordForm.buyerUserId" disabled />
        </el-form-item>
        <el-form-item label="支付密码" prop="payPassword">
          <el-input 
            v-model="payPasswordForm.payPassword" 
            placeholder="请输入6位数字支付密码" 
            type="password"
            maxlength="6"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPayPassword">
          <el-input 
            v-model="payPasswordForm.confirmPayPassword" 
            placeholder="请再次输入6位数字支付密码" 
            type="password"
            maxlength="6"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePayPassword">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 实名认证信息对话框 -->
    <el-dialog 
      title="实名认证信息" 
      v-model="authDialogVisible" 
      width="600px"
    >
      <el-form 
        label-width="120px" 
        size="small"
      >
        <el-form-item label="用户ID">
          <el-input v-model="authForm.userId" disabled />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="authForm.realName" disabled />
        </el-form-item>
        <el-form-item label="证件类型">
          <el-input :value="authForm.idCardType === 1 ? '身份证' : authForm.idCardType === 2 ? '护照' : authForm.idCardType === 3 ? '港澳通行证' : '未知'" disabled />
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="authForm.idCardNumber" disabled />
        </el-form-item>
        <el-form-item label="人脸照片">
          <el-image 
            v-if="authForm.idCardHandheld"
            :src="authForm.idCardHandheld" 
            style="width: 200px; height: 200px"
            fit="cover"
            preview-teleported
            :preview-src-list="[authForm.idCardHandheld]"
          >
            <template #error>
              <div class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
          <span v-else>无图片</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="authDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { UserService, UserInfo, UserInfoListParams } from '@/api/userApi'
import { encrypt } from '@/utils/rsaEncrypt'
import request from '@/utils/http'
import { BaseResult } from '@/types/axios'

// 搜索表单
const searchForm = reactive<UserInfoListParams>({
  page: 1,
  pageSize: 10,
  buyerUserId: undefined,
  phone: '',
  userAccount: '', // 添加用户账号查询字段
  state: undefined,
  isBlack: undefined,
  startTime: '',
  endTime: ''
})

// 注册时间范围
const registerTimeRange = ref<[string, string]>(['', ''])

// 表格数据
const tableData = ref<UserInfo[]>([])
const total = ref(0)
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 编辑表单
const editForm = reactive<UserInfo>({
  buyerUserId: undefined,
  name: '',
  sex: '',
  birthday: '',
  age: undefined,
  phone: '',
  headImage: '',
  backgroundImage: '',
  state: 1,
  ifBlack: 0,
  remark: '',
  province: '',
  city: '',
  userAccount: '',
  password: '',
  createTime: ''
})

// 表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,16}$/, message: '昵称格式不正确', trigger: 'blur' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' }
  ],
  state: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 表单引用
const editFormRef = ref<FormInstance>()
const payPasswordFormRef = ref<FormInstance>()

// 修改支付密码对话框
const payPasswordDialogVisible = ref(false)

// 支付密码表单
const payPasswordForm = reactive({
  buyerUserId: '',
  payPassword: '',
  confirmPayPassword: ''
})

// 实名认证审核对话框
const authDialogVisible = ref(false)
const authForm = reactive({
  userId: '',
  realName: '',
  idCardType: 0,
  idCardNumber: '',
  idCardHandheld: ''
})

// 审核结果
const authResult = ref<number>()
const authRemark = ref('')

// 支付密码表单验证规则
const payPasswordRules = {
  payPassword: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字支付密码', trigger: 'blur' }
  ],
  confirmPayPassword: [
    { required: true, message: '请确认支付密码', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (value !== payPasswordForm.payPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息列表
const getUserInfoList = async () => {
  loading.value = true
  try {
    
    const params = { ...searchForm }
    // 处理注册时间范围
    if (registerTimeRange.value && registerTimeRange.value.length === 2) {
      params.startTime = registerTimeRange.value[0]
      params.endTime = registerTimeRange.value[1]
    } else {
      delete params.startTime
      delete params.endTime
    }
    
    // 清理空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined || params[key] === null) {
        delete params[key]
      }
    })
    
    const res = await UserService.getUserInfoList(params)
    if (res.code === "200") {
      tableData.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取用户信息列表失败')
    }
  } catch (error) {
    console.error('获取用户信息列表失败:', error)
    ElMessage.error('获取用户信息列表失败')
  } finally {
    loading.value = false
  }
}

// 监听注册时间范围变化
watch(registerTimeRange, () => {
  // 时间范围变化时可以自动搜索，或者保持现有逻辑
})

// 搜索
const handleSearch = () => {
  searchForm.page = 1
  getUserInfoList()
}

// 重置
const handleReset = () => {
  searchForm.buyerUserId = undefined
  searchForm.phone = ''
  searchForm.userAccount = '' // 重置用户账号
  searchForm.state = undefined
  searchForm.isBlack = undefined
  searchForm.startTime = ''
  searchForm.endTime = ''
  registerTimeRange.value = ['', '']
  searchForm.page = 1
  getUserInfoList()
}

// 编辑
const handleEdit = (row: UserInfo) => {
  dialogTitle.value = '修改用户信息'
  isEdit.value = true
  Object.assign(editForm, row)
  dialogVisible.value = true
}

// 保存
const handleSave = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (isEdit.value) {
          // 编辑
          res = await UserService.updateUserInfo(editForm)
        }
        
        if (res.code === "200") {
          ElMessage.success('编辑成功')
          dialogVisible.value = false
          getUserInfoList()
        } else {
          ElMessage.error(res.message || '编辑失败')
        }
      } catch (error) {
        console.error('编辑失败:', error)
        ElMessage.error('编辑失败')
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  editFormRef.value?.resetFields()
}

// 打开修改支付密码对话框
const handleModifyPayPassword = (row: UserInfo) => {
  payPasswordForm.buyerUserId = row.buyerUserId?.toString() || ''
  payPasswordForm.payPassword = ''
  payPasswordForm.confirmPayPassword = ''
  payPasswordDialogVisible.value = true
}

// 保存支付密码
const handleSavePayPassword = async () => {
  if (!payPasswordFormRef.value) return
  
  await payPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 使用RSA加密支付密码
        const encryptedPayPassword = encrypt(payPasswordForm.payPassword)
        const encryptedConfirmPayPassword = encrypt(payPasswordForm.confirmPayPassword)
        
        // 检查加密结果
        if (!encryptedPayPassword || !encryptedConfirmPayPassword) {
          ElMessage.error('密码加密失败，请重试')
          return
        }
        
        const res = await UserService.adminModifyPayPassword({
          buyerUserId: Number(payPasswordForm.buyerUserId),
          encryptedPayPassword: encryptedPayPassword,
          encryptedConfirmPayPassword: encryptedConfirmPayPassword
        })
        
        if (res.code === "200") {
          ElMessage.success('修改支付密码成功')
          payPasswordDialogVisible.value = false
        } else {
          ElMessage.error(res.message || '修改支付密码失败')
        }
      } catch (error) {
        console.error('修改支付密码失败:', error)
        ElMessage.error('修改支付密码失败')
      }
    }
  })
}

// 关闭支付密码对话框
const handlePayPasswordDialogClose = () => {
  payPasswordFormRef.value?.resetFields()
}

// 分页相关
const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  searchForm.page = 1
  getUserInfoList()
}

const handleCurrentChange = (val: number) => {
  searchForm.page = val
  getUserInfoList()
}

// 获取实名认证状态文本
const getAuthStatusText = (status?: number): string => {
  switch (status) {
    case 0:
      return '未认证'
    case 1:
      return '审核中'
    case 2:
      return '已认证'
    case 3:
      return '认证失败'
    default:
      return '未认证'
  }
}

// 获取实名认证状态标签类型
const getAuthStatusTagType = (status?: number): string => {
  switch (status) {
    case 0:
      return ''
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'danger'
    default:
      return ''
  }
}

// 获取实名认证信息
const getAuthInfo = async (userId: number) => {
  console.log('即将发送请求')
  try {
    const res = await UserService.getAuthInfo(userId)
    console.log('请求已发送')
    if (res.code === "200" && res.data) {
      authForm.userId = res.data.userId || ''
      authForm.realName = res.data.realName || ''
      authForm.idCardType = res.data.idCardType || 0
      authForm.idCardNumber = res.data.idCardNumber || ''
      authForm.idCardHandheld = res.data.idCardHandheld || ''
      authDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取实名认证信息失败')
    }
  } catch (error) {
    console.error('获取实名认证信息失败:', error)
    ElMessage.error('获取实名认证信息失败')
  }
}

// 处理实名认证审核
const handleAuthCheck = (row: UserInfo) => {
  getAuthInfo(row.buyerUserId as number)
}

// 提交审核结果
const submitAuthResult = async () => {
  try {
    // 这里需要根据实际接口实现提交审核结果的逻辑
    // 目前只是模拟成功
    ElMessage.success('审核结果已提交')
    authDialogVisible.value = false
    // 重置表单
    authResult.value = undefined
    authRemark.value = ''
    // 刷新列表
    getUserInfoList()
  } catch (error) {
    console.error('提交审核结果失败:', error)
    ElMessage.error('提交审核结果失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getUserInfoList()
})
</script>

<style scoped>
.user-info-container {
  padding: 20px;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
  padding: 20px;
}

/* 优化搜索表单布局 */
:deep(.search-card .el-form-item) {
  margin-right: 15px;
  margin-bottom: 15px;
}

/* 优化表格样式 */
:deep(.el-table) {
  border-collapse: collapse;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  font-size: 13px;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 12px 0;
  font-size: 13px;
}

/* 优化操作列按钮样式 */
:deep(.el-table .el-button) {
  padding: 6px 10px;
  height: 30px;
  line-height: 1;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  
  /* 确保页码字体样式与用户管理界面保持一致 */
  :deep(.el-pagination) {
    font-weight: normal;
  }
  
  :deep(.el-pagination .el-pager li) {
    font-weight: normal;
  }
  
  :deep(.el-pagination .el-pager li.active) {
    font-weight: bold;
  }
  
  /* 添加hover状态样式确保一致性 */
  :deep(.el-pagination .el-pager li:hover) {
    color: #409eff;
  }
  
  :deep(.el-pagination .el-pager li.active:hover) {
    color: #fff;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 15px;
}

/* 优化对话框内表单样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog .el-form-item) {
  margin-bottom: 16px;
}

/* 优化头像显示 */
:deep(.el-image) {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 优化标签样式 */
:deep(.el-tag) {
  padding: 4px 8px;
  font-size: 12px;
}
</style>